package groupon.com.validator;

import groupon.common.util.AppUtil;
import groupon.user.bo.service.ManagerUserService;
import groupon.user.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class UserFormValidator implements Validator{

	@Autowired
	private ManagerUserService _managerUserService;
	
	@Override
	public boolean supports(Class<?> arg0) {
		return User.class.equals(arg0);
	}

	@Override
	public void validate(Object obj, Errors error) {
		User user = (User)obj;
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "username", "field.required","User Name is required");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "firstName", "field.required","First Name is required");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "lastName", "field.required","Last Name is required");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "email", "field.required","Email is required");
		ValidationUtils.rejectIfEmptyOrWhitespace(error, "birthday", "field.required","Birthday is required");
		if(!AppUtil.isNullOrEmpty(user.getUsername())){
			User checkUser = _managerUserService.findUserByUsernameOrEmail(user.getUsername(), null);
			if(checkUser != null && checkUser.getUsername() != null){
				error.rejectValue("username","field.required","This user really exist");
			}
		}
		if(!AppUtil.isNullOrEmpty(user.getEmail())){
			if(!AppUtil.checkFormatEmail(user.getEmail())){
				error.rejectValue("email", "field.required", "Email wrong format");
			}else{
				User checkUser = _managerUserService.findUserByUsernameOrEmail(null, user.getEmail());
				if(checkUser != null && checkUser.getEmail() != null){
					error.rejectValue("email","field.required","This email really exist");
				}
			}
		}
	}
}
